#!/bin/bash

# WebSocket聊天应用服务器端一键部署脚本
# 使用方法: ./deploy-server.sh

set -e

echo "=== WebSocket聊天应用部署开始 ==="

# 检查必要文件
echo "检查部署文件..."
if [ ! -f "Dockerfile.publish" ]; then
    echo "❌ 错误: Dockerfile.publish 文件不存在"
    exit 1
fi

if [ ! -f "docker-compose.publish.yml" ]; then
    echo "❌ 错误: docker-compose.publish.yml 文件不存在"
    exit 1
fi

if [ ! -d "publish" ]; then
    echo "❌ 错误: publish 目录不存在"
    echo "请确保上传了完整的 publish 目录！"
    exit 1
fi

if [ ! -f "publish/hao-Chat.Api.dll" ]; then
    echo "❌ 错误: publish/hao-Chat.Api.dll 文件不存在"
    echo "请重新发布项目并上传 publish 目录！"
    exit 1
fi

echo "✅ 所有必要文件检查通过"

# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
    echo "正在安装Docker..."
    curl -fsSL https://get.docker.com -o get-docker.sh
    sh get-docker.sh
    systemctl start docker
    systemctl enable docker
    echo "Docker安装完成"
fi

# 检查Docker Compose是否安装
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
    echo "正在安装Docker Compose..."
    # 使用包管理器安装（更稳定）
    if command -v yum &> /dev/null; then
        # CentOS/RHEL
        yum install -y docker-compose-plugin
    elif command -v apt &> /dev/null; then
        # Ubuntu/Debian
        apt update && apt install -y docker-compose-plugin
    else
        # 备用方案：直接下载稳定版本
        echo "使用备用安装方案..."
        curl -L "https://github.com/docker/compose/releases/download/v2.21.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
        chmod +x /usr/local/bin/docker-compose
    fi
    echo "Docker Compose安装完成"
else
    echo "Docker Compose已安装"
fi

# 获取服务器公网IP
echo "正在获取服务器IP地址..."
SERVER_IP=$(curl -s ifconfig.me || curl -s ipinfo.io/ip || curl -s icanhazip.com)
if [ -z "$SERVER_IP" ]; then
    echo "警告: 无法自动获取公网IP，请手动输入服务器IP地址:"
    read -p "服务器IP: " SERVER_IP
fi
echo "服务器IP: $SERVER_IP"

# 修改配置文件中的IP地址
echo "正在更新配置文件..."
if [ -f "publish/config.js" ]; then
    # 备份原配置文件
    cp publish/config.js publish/config.js.backup
    
    # 替换IP地址
    sed -i "s/192\.168\.1\.100/$SERVER_IP/g" publish/config.js
    echo "配置文件已更新"
else
    echo "警告: 未找到config.js文件"
fi

# 停止现有容器
echo "正在停止现有容器..."
docker compose -f docker-compose.publish.yml down 2>/dev/null || true

# 构建并启动容器
echo "正在构建并启动容器..."
docker compose -f docker-compose.publish.yml up -d --build

# 等待容器启动
echo "等待容器启动..."
sleep 10

# 检查Docker服务状态
echo "检查Docker服务状态..."
if ! docker info >/dev/null 2>&1; then
    echo "❌ Docker服务未运行，请启动Docker服务"
    exit 1
fi

# 检查容器状态
echo "检查容器状态..."
if docker ps | grep -q "websocket-chat-app"; then
    echo "✅ 容器启动成功"
else
    echo "❌ 容器启动失败，查看日志:"
    docker compose -f docker-compose.publish.yml logs
    echo ""
    echo "容器状态检查:"
    docker ps -a | grep websocket-chat-app || echo "未找到容器"
    exit 1
fi

# 开放防火墙端口
echo "正在配置防火墙..."
if command -v ufw &> /dev/null; then
    sudo ufw allow 8083 2>/dev/null || echo "防火墙配置可能需要手动处理"
elif command -v firewall-cmd &> /dev/null; then
    sudo firewall-cmd --permanent --add-port=8083/tcp 2>/dev/null || echo "防火墙配置可能需要手动处理"
    sudo firewall-cmd --reload 2>/dev/null || true
fi

# 显示部署结果
echo ""
echo "=== 部署完成 ==="
echo "应用访问地址: http://$SERVER_IP:8083"
echo "WebSocket端点: ws://$SERVER_IP:8083/ws"
echo ""
echo "验证步骤:"
echo "1. 检查容器状态: docker ps"
echo "2. 查看应用日志: docker compose -f docker-compose.publish.yml logs"
echo "3. 测试本地访问: curl http://localhost:8083"
echo "4. 在浏览器中访问: http://$SERVER_IP:8083"
echo ""
echo "如需停止应用: docker compose -f docker-compose.publish.yml down"
echo "如需重启应用: docker compose -f docker-compose.publish.yml restart"